<?php

function doCommunication($GETCOMMETH, $PID, $FileRoot) {
    /*
      Transact FT FTP Client Versão 0.1
      ### passar a objecto de ligacao ftp
     */

    $TrsResultCode = 0;
    $_handling_connection_status = null;
    $ftp_channel = $GETCOMMETH[1]['tcmtChannel'];

    if ($GETCOMMETH[1]['tcmtLinkMode'] != 'ACTIVE') {
        $_handling_connection_status = 'Unauthorized communication';
    } else {

        # Include Local FTP Server Settings
        include($GLOBALS['LIB'] . '../Configuration/tft_config/local_config.php');
        # Include Remote FTP Server Settings
        if (file_exists($GLOBALS['LIB'] . '../Configuration/tft_config/corresp_' . $GETCOMMETH[1]['CorrAgente'] . '_config.php')) {
            include($GLOBALS['LIB'] . '../Configuration/tft_config/corresp_' . $GETCOMMETH[1]['CorrAgente'] . '_config.php');

            $LocalIncomingDocument_Folder = $FileRoot . "/" . $GETCOMMETH[1]['CorrAgente'] . "/IN";
            $LocalOutgoing_Document_Folder = $FileRoot . "/" . $GETCOMMETH[1]['CorrAgente'] . "/OUT";

            #### End Connection Settings ####
            # Connect
            $conn_id = ftp_connect($remote_Server, $remote_ServerPort);
            // set up basic ssl connection
            //$conn_id = ftp_ssl_connect($ftp_server);
            # Login to FTP Server
            if (!$conn_id) {
                $_handling_connection_status = "ERRO:FTP_CONNECTION";
            } else {

                if (true === ($login_result = ftp_login($conn_id, $remote_user, $remote_pass))) {

                    #ftp_pasv($conn_id, true);
                    $_handling_connection_status = 1;

                    if ($GETCOMMETH[1]['tcmtCorrPNAME'] == 'Put') {
                        $LocalDir = null;
                        $item = null;
                        $FileLocal_RemoteName = null;
                        $FileLocal = null;

                        #### Check for outgoing transactions
                        /* if(ftp_chdir($conn_id,$LocalOutgoing_Document_Folder)){
                          $buffer_transactions = ftp_nlist($conn_id,'.'); */

                        if ($LocalDir = opendir($LocalOutgoing_Document_Folder)) {
                            $_handling_connection_status = "EMPTY";
                            $TrsResultCode = 0;
                            while (false !== ($item = readdir($LocalDir))) {
                                if ($item != '.' && $item != '..') {
                                    $FileLocal = $LocalOutgoing_Document_Folder . "/" . $item;
                                    $FileLocal_RemoteName = $OutgoingDocument_Folder . "/" . basename($FileLocal);
                                    if ($_handling_connection_status != "ERR1") {
                                        # Verify Transaction
                                        if (!ftp_put($conn_id, $FileLocal_RemoteName, $FileLocal, FTP_BINARY)) {
                                            $_handling_connection_status = "ERR1";
                                        } else {
                                            # check for filesize
                                            unlink($FileLocal);
                                            $_handling_connection_status = "UPOK";
                                            $TrsResultCode = 2;
                                        }
                                    }
                                }
                            }
                        } else {
                            $_handling_connection_status = "ERRPATH";
                        }
                    }
                    if ($GETCOMMETH[1]['tcmtCorrPNAME'] == 'Get') {
                        # Saltar passo # Desactivado Get de Transaccoes

                        $LocalDir = null;
                        $item = null;
                        $FileLocal_RemoteName = null;
                        $FileLocal = null;
                        #### Check for incoming transactions
                        if (ftp_chdir($conn_id, $IncomingDocument_Folder)) {

                            $buffer_transactions = ftp_nlist($conn_id, '.');

                            $TrsResultCode = 0;
                            foreach ($buffer_transactions AS $item) {

                                $item_size = ftp_size($conn_id, $item);
                                if ("$item_size" != "-1") {
                                    $FileLocal = $item;
                                    $FileLocal_RemoteName = $LocalIncomingDocument_Folder . "/" . basename($FileLocal);

                                    # Verify Transaction
                                    if (!ftp_get($conn_id, $FileLocal_RemoteName, $FileLocal, FTP_BINARY)) {
                                        $_handling_connection_status = "ERR";
                                    } else {
                                        ftp_delete($conn_id, $FileLocal);
                                        $_handling_connection_status = "DWOK";
                                        $TrsResultCode = 2;
                                    }
                                }
                            }
                        } else {
                            $_handling_connection_status = "ERRPATH.";
                        }
                    }
                    if (!isset($TrsResultCode)) {
                        $TrsResultCode = 0;
                    }
                } else {
                    $_handling_connection_status = "ERRO:FTP_CONNECTION: Attempted to connect to $remote_Server for user $remote_user";
                }

                # End Client Session
                ftp_close($conn_id); // Close the FTP Connection
            }
        } else {
            $_handling_connection_status = "NO_CONFIG_FOUND";
            $TrsResultCode = 0;
        }
    }
    if ($TrsResultCode != 2) {
        $tlDocument_ERR = $_handling_connection_status;
        return $tlDocument_ERR;
    } else {

    }
    return $TrsResultCode;
}

function IncomeTransact_LoadFile($Channel, $DocumentDir, $CorrIncomeDir, $PID, $PIDPrefix) {

    if (is_dir($DocumentDir . "/" . $CorrIncomeDir . "/IN/")) {
        if ($Channel == 2) {
            $handle = opendir($DocumentDir . "/" . $CorrIncomeDir . "/IN/");

            while (false !== ($file = readdir($handle))) {
                if ($file != '.' && $file != '..' && (substr($file, strlen($file) - 6, 2) == $PIDPrefix[0] || substr($file, 0, 2) == $PIDPrefix[1])) {
                    $FileList[] = $file;
                }
            }
            if (isset($FileList)) {
                sort($FileList);
                return $FileList;
            } else {
                return null;
            }
        } else {
            return null;
        }
    } else {
        return null;
    }
}

function IncomeTransact_StoreFile($TrResult, $DocumentDir, $CorrIncomeDir, $file, $StoreDir) {
    # Arquiva ficheiro

    if ($CorrIncomeDir != '') {
        $Store_Status = 0;

        if ($TrResult == 2) {
            if (copy($DocumentDir . "/" . $CorrIncomeDir . "/IN/" . $file, $StoreDir . "TRANSACT/INCOME/" . $file)) {
                $Store_Status = 1;
            }
        } elseif ($TrResult < 2) {
            if (copy($DocumentDir . "/" . $CorrIncomeDir . "/IN/" . $file, $StoreDir . "TRANSACT/INCOME_REJECTED/" . $file)) {
                $Store_Status = 1;
            }
        }
        if ($Store_Status == 1) {
            if (unlink($DocumentDir . "/" . $CorrIncomeDir . "/IN/" . $file)) {
                $Store_Status = 2;
            }
        }
        /*
          problema mostrar multiplos resultados
          num icone de resultado do processo
         */
        if ($Store_Status < 2) {
            return $error = 'Erro a copiar ficheiro.';
        }
        if ($TrResult != 2) {
            return $error = 'Uma ou mais transaccoes falharam.';
        }
    } else {
        return $error = 'Erro configuracao de Correspondente.';
    }
}

function transaction_filenames($dir, $time, $id, $corr, $format_string, $ext) {

    $filename_formated = $format_string;

    #Insere Data
    $filename_formated = str_replace("{YYYY}", substr($time, 0, 4), $filename_formated);
    $filename_formated = str_replace("{MM}", substr($time, 5, 2), $filename_formated);
    $filename_formated = str_replace("{DD}", substr($time, 8, 2), $filename_formated);
    $filename_formated = str_replace("{HH}", substr($time, 11, 2), $filename_formated);
    $filename_formated = str_replace("{II}", substr($time, 14, 2), $filename_formated);
    $filename_formated = str_replace("{SS}", substr($time, 16, 2), $filename_formated);

    $filename_formated = str_replace("{CORRCODE}", $corr, $filename_formated);

    #Insere ID Transaction
    $filename_formated = str_replace("{TRANSACTIONID}", $id, $filename_formated);
    #Insere ID Versao
    $filename_formated = str_replace("{VERSION}", 1, $filename_formated);

    #Insere ID Incidencia
    $filename_formated = str_replace("{TRANSACTIONINCIDENT}", 1, $filename_formated);

    #check if file exists
    if (file_exists($dir . $filename_formated) && $filename_formated != '') {
        if (strpos("{VERSION}", $format_string) === true) {
            #Get last version from file
            $version = preg_split('{VERSION}', $format_string);
            $version = substr($filename_formated, strlen($version[0]), strlen($filename_formated) - $version[1]);

            #Insere ID Versao
            $filename_formated = str_replace("{VERSION}", $version + 1, $format_string);
        } elseif ($dir != '') {
            rename($filename_formated, $filename_formated . '_del' . date("his"));
        }
    }
    return $filename_formated . '.' . $ext;
}

function transaction_filenamereturn($filename, $format_string) {

    $file_corrcode = '';
    $file_transactid = '';
    $file_date = '';
    $file_time = '';

    $GetFilestringElements = preg_split('/[_]/', $format_string);
    $GetFilenameElements = preg_split('/[_.]/', $filename);

    if (count($GetFilestringElements) !== count($GetFilenameElements) - 1) {
        $error = 'Ficheiro invalido.';
    } else {

        for ($al = 0; $al < count($GetFilestringElements); $al++) {

            if (!in_array(substr($GetFilestringElements[$al], 0, 1), array('{', '6'))) {
                if ($GetFilestringElements[$al] == $GetFilenameElements[$al]) {
                    $file_transaction = $GetFilenameElements[$al];
                } else {
                    $error = 'Invalid TransactionFile Prefix.';
                }
            } elseif ($GetFilestringElements[$al] == '{DD}{MM}{YYYY}' || $GetFilestringElements[$al] == '{MM}{DD}{YYYY}' || $GetFilestringElements[$al] == '{YYYY}{MM}{DD}') {
                if (strlen($GetFilenameElements[$al]) == 8) {
                    if ($GetFilestringElements[$al] == '{DD}{MM}{YYYY}') {
                        $file_date = substr($GetFilenameElements[$al], 4, 4) . '-' . substr($GetFilenameElements[$al], 2, 2) . '-' . substr($GetFilenameElements[$al], 0, 2);
                    } elseif ($GetFilestringElements[$al] == '{MM}{DD}{YYYY}') {
                        $file_date = substr($GetFilenameElements[$al], 4, 4) . '-' . substr($GetFilenameElements[$al], 0, 2) . '-' . substr($GetFilenameElements[$al], 2, 2);
                    } elseif ($GetFilestringElements[$al] == '{YYYY}{MM}{DD}') {
                        $file_date = substr($GetFilenameElements[$al], 0, 4) . '-' . substr($GetFilenameElements[$al], 4, 2) . '-' . substr($GetFilenameElements[$al], 6, 2);
                    }
                } else {
                    $error = 'Invalid TransactionFile Date.';
                }
            } elseif ($GetFilestringElements[$al] == '{HH}{II}') {
                if (strlen($GetFilenameElements[$al]) == 4) {
                    $file_time = substr($GetFilenameElements[$al], 0, 2) . ':' . substr($GetFilenameElements[$al], 2, 2) . ':00';
                } else {
                    $error_time = 'Transaction Time is required.';
                    $error = 'Invalid TransactionFile Time.';
                }
            } elseif ($GetFilestringElements[$al] == '{YYYY}') {
                if (strlen($GetFilenameElements[$al]) == 4) {
                    $file_year = $GetFilenameElements[$al];
                } else {
                    $error = 'Invalid TransactionFile Year.';
                }
            } elseif ($GetFilestringElements[$al] == '{MM}') {
                if (strlen($GetFilenameElements[$al]) == 2) {
                    $file_month = $GetFilenameElements[$al];
                } else {
                    $error = 'Invalid TransactionFile Month.';
                }
            } elseif ($GetFilestringElements[$al] == '{DD}') {
                if (strlen($GetFilenameElements[$al]) == 2) {
                    $file_day = $GetFilenameElements[$al];
                } else {
                    $error = 'Invalid TransactionFile Day.';
                }
            } elseif ($GetFilestringElements[$al] == '{HH}') {
                if (strlen($GetFilenameElements[$al]) == 2) {
                    $file_hour = $GetFilenameElements[$al];
                } else {
                    $error = 'Invalid TransactionFile Hour.';
                }
            } elseif ($GetFilestringElements[$al] == '{II}') {
                if (strlen($GetFilenameElements[$al]) == 2) {
                    $file_minute = $GetFilenameElements[$al];
                } else {
                    $error = 'Invalid TransactionFile Minute.';
                }
            } elseif ($GetFilestringElements[$al] == '{SS}') {
                if (strlen($GetFilenameElements[$al]) == 2) {
                    $file_second = $GetFilenameElements[$al];
                } else {
                    $error = 'Invalid TransactionFile Date.';
                }
            } elseif ($GetFilestringElements[$al] == '{CORRCODE}') {
                if (strlen($GetFilenameElements[$al]) <= 4) {
                    $file_corrcode = $GetFilenameElements[$al];
                } else {
                    $error = 'Invalid TransactionFile CorrCode.';
                }
            } elseif (in_array($GetFilestringElements[$al], array('{TRANSACTIONID}', '6950{TRANSACTIONID}'))) {
                $GetFilenameElements[$al] = (int) substr($GetFilenameElements[$al], strlen($GetFilenameElements[$al]) - 10, strlen($GetFilenameElements[$al]));
                if (strlen($GetFilenameElements[$al]) <= 10 || !is_int($GetFilenameElements[$al])) {
                    $file_transactid = $GetFilenameElements[$al];
                } else {
                    $error = 'Invalid TransactionFile ID.';
                }
            } elseif ($GetFilestringElements[$al] == '{VERSION}') {
                if (strlen($GetFilenameElements[$al]) <= 1 || !is_int($GetFilenameElements[$al])) {
                    $file_version = $GetFilenameElements[$al];
                } else {
                    $error = 'Invalid TransactionFile Version.';
                }
            }
        }
        if ($file_date == '' && isset($file_year) && isset($file_month) && isset($file_day)) {
            $file_date = $file_year . '-' . $file_month . '-' . $file_day;
        } elseif (!isset($file_date) || strlen($file_date) != 10) {
            $error = 'Invalid Transactionfile Date';
        }
        if ($file_time == '' && isset($file_hour) && isset($file_minute)) {
            $file_time = $file_hour . ':' . $file_minute . ':00';
        } elseif ($file_time == '' && isset($error_time) || strlen($file_time) != 8 && strlen($file_time) > 0) {
            $error = 'Invalid Transactionfile Time';
        }
    }
    if (isset($error)) {
        return array('err', $error);
    } else {

        $file_properties[] = $file_corrcode;
        $file_properties[] = $file_transactid;
        $file_properties[] = $file_date;
        $file_properties[] = $file_time;
        return $file_properties;
    }
}

function IncomeIncident($file, $dir1, $subdir, $corrparams, $PID, $GetMethodParams) {
    global $sysTime, $SESSID;
    $Status = 0;

    $handle = fopen($dir1 . "/" . $subdir . "/IN/" . $file, "r");

    #Pre-set Vars
    $SUMREFA = 0;
    $SUMSENT = 0;

    $BankCheck = '';
    CONN('MYT');
    $FILESEP[] = array('', ',', ';', '	');
    $fileprp[] = substr($file, 0, 3);
    $TransactionVersionID = explode('.',$file);
    $TransactionVersionID = explode('_',$TransactionVersionID[0]);
    $TransactionVersionID = (int)$TransactionVersionID[5];
    #	Valida
    $CorrProperties = $GLOBALS['MYT']->db_array("SELECT CorrNumero, CorrFormatoFichero, CorrAlias, CorrAgente, EXT, DELIMITER, DELIMITER, OB, VERSION, LENGTH, METRIC, ffFilenameFormat FROM corresponsales
													LEFT OUTER JOIN hd_fileformats ON REF = CorrFormatoFichero WHERE CorrAgente = '{$corrparams[1]['CorrAgente']}'");

    if (!isset($CorrProperties[1])) {
        #Gerar alerta, Recebida transaccao de correspondente inexiste ou com configuracao incorrecta
        echo "Invalid request";
    } else {
        if ($fileprp[0] != $CorrProperties[1]['CorrAgente']) {
            $Msg_ERROR = 'O ficheiro nao e valido.';
        }
        $Status = 1;
        $ReceivedDate = substr($sysTime, 0, 10);
        $ReceivedTime = substr($sysTime, 11, 18);

        $HandledFile = $GLOBALS['BIB'] . 'FileTemplates/TransactModels/' . $CorrProperties[1]['DELIMITER'] . '_' . $CorrProperties[1]['EXT'] . '_' . $CorrProperties[1]['OB'] . '_' . $CorrProperties[1]['VERSION'] . '_' . $PID . '.php';

        if ($CorrProperties[1]['EXT'] != 'xml') {
            while (($data = fgetcsv($handle, 2048, ';')) !== FALSE) {
                include($HandledFile);
            }
        } else {
            $data_contents = xml_getparse(file_get_contents($dir1 . "/" . $subdir . "/IN/" . $file, true));
            $data_count = count($data_contents);
            for ($row = 1; $row <= $data_count; $row++) {
                $data = $data_contents['Incident'];
                include($HandledFile);
                $data['CodeTransaction'] = (int) substr($data['CodeTransaction'], strlen($data['CodeTransaction']) - 10, strlen($data['CodeTransaction']));
            }
        }
        fclose($handle);
        #       Verifica

		$GET = $GLOBALS['MYT']->db_array("SELECT FraID, FraIciCorrReferenceIci FROM facturas
                                               INNER JOIN facturas_income ON FraID = FraIncID
                                               LEFT JOIN facturas_incidencias ON FraIciID = FraID AND FraIciCorrReferenceIci = {$data['CodeIncident']} AND FraIciVersion = $TransactionVersionID
                                          WHERE FraIncCorresponsal = {$corrparams[1]['CorrNumero']} AND FraIncReferenciaCo = {$data['CodeTransaction']}");
        if (isset($GET[1])) {
            if ($GET[1]['FraIciCorrReferenceIci'] != '') {
               $error = 'Erro: incidencia ja registada';
            }
            if (!isset($error)) {
                #	Regista Alteracao
                $row = tuga_multiquery("CALL fn_incidence (@IncidentID,{$GET[1]['FraID']},'$sysTime',$_SESSION[$SESSID],'{$data['IncidentDescription']}',2,'{$FraPosition[$data['FieldToModify']['FieldName']][0]}','{$data['FieldToModify']['FieldOldValue']}','{$data['FieldToModify']['FieldNewValue']}',$TransactionVersionID,{$data['CodeIncident']}); SELECT @IncidentID");
                $Msg_CONF = $row[0][0];
                if($row[0][0]>0){$Status = 2;}
            }
        } else {
           $error = 'Nao foi encontrada transaccao';
        }
    }
    IncomeTransact_StoreFile($Status, $dir1, $subdir, $file, $GLOBALS['DOC']);
    if (isset($error)) {
        return $error;
    } else {
        return $Status;
    }
}